import axios from 'axios'
import router from '../router'
import { Message } from 'element-ui'

const instance = axios.create({
  baseURL: process.env.NODE_ENV != 'production' ? process.env.VUE_APP_BASE_API : process.env.VUE_APP_SERVER_URL,
  timeout: 10000,
  withCredentials: true
})

instance.interceptors.request.use(config => {
  const token = localStorage.getItem('wft-token')
  if(token) {
    config.headers.Authorization = token
  }
  return config
}, error => {
  console.error(error)
})

instance.interceptors.response.use(response => {
  return response
}, error => {
  if (error.response) {
    if (error.response.status === 401) {
      Message.warning('登录超时，请重新登录')
      router.replace('/login')
    } else if (error.response.status === 402 || error.response.status === 403) {
      Message.warning('登录超时，请重新登录')
      router.replace('/login')
    } else if (error.response.status === 404) {
      Message.warning('路径找不到~~~')
    }
  } else {
    if (!window.navigator.onLine) {
      Message.warning('请检查当前网络设置')
      // 断网处理
      // 跳转到断网页面
    }
    return Promise.reject(error)
  }
})

export default instance